<template>
  <div class="wanxiang-container">
    <div class="left-panel">
      <h1 class="page-title">通义万相</h1>
      <div class="input-section">
        <div class="prompt-input">
          <el-input
            type="textarea"
            v-model="prompt"
            :autosize="{ minRows: 3, maxRows: 6 }"
            placeholder="请输入图片描述，例如：一只奔跑在雪地上的灰狼，背景是雪山和森林"
            @keydown.enter.native.prevent="handleEnterKey"
            class="custom-input"
          ></el-input>
        </div>

        <div class="options-panel">
          <div class="option-group">
            <div class="option-title">比例尺寸</div>
            <div class="size-options">
              <div
                  v-for="option in sizeOptions"
                  :key="option.value"
                  class="size-option"
                  :class="{ 'is-active': imageRatio === option.value }"
                  @click="imageRatio = option.value"
              >
                {{ option.label }}
              </div>
            </div>
          </div>
          <div class="option-group">
            <div class="option-title">图像风格</div>
            <div class="style-options">
              <div
                  v-for="option in styleOptions"
                  :key="option.value"
                  class="style-option"
                  :class="{ 'is-active': selectedStyle === option.value }"
                  @click="selectedStyle = option.value"
              >
                {{ option.label }}
              </div>
            </div>
          </div>
        </div>
        <div class="options-panel">
          <div class="option-group">
            <div class="option-title">上传垫图</div>

            <FileUpload v-model="ref_img"/>
          </div>
          <div class="option-group">
            <div class="option-title">生成数量</div>
            <div class="size-options">
              <el-input-number
                  v-model="imageCount"
                  :min="1"
                  :max="4"
                  size="small"
                  controls-position="right"
              ></el-input-number>
            </div>
          </div>

        </div>
      </div>
      <div class="button-group">
        <el-button
            type="primary"
            @click="generateImage"
            :loading="isGenerating"
            :disabled="!prompt.trim()"
            class="generate-btn"
        >
          生成图片
        </el-button>
      </div>
    </div>

    <div class="right-panel">
      <div v-if="images.length > 0" class="gallery-section">
        <div class="image-grid" :class="{'single-image': images.length === 1}">
          <div
            v-for="(image, index) in images"
            :key="index"
            class="image-item"
          >
            <el-image
              :src="image"
              fit="cover"
              :preview-src-list="[image]"
            >
              <template #placeholder>
                <div class="image-placeholder">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </template>
            </el-image>
            <div class="image-actions">
              <el-button
                type="text"
                icon="el-icon-download"
                @click="downloadImage(image, index)"
              >
                下载
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <div class="empty-state" v-else>
        <i class="el-icon-picture-outline"></i>
        <p v-if="isGenerating">
          正在生成<span style="color: #0bc162">{{ task_metrics.SUCCESS }}</span>/{{ task_metrics.TOTAL }}张图像...
        </p>
        <p v-else>输入描述并点击生成按钮开始创作</p>
      </div>
    </div>
  </div>
</template>

<script>
import FileUpload from "@/components/FileUpload.vue";
import axios from "axios";

export default {
  name: 'WanxiangView',
  components: {FileUpload},
  data() {
    return {
      prompt: '',
      images: [],
      isGenerating: false,
      imageRatio: '1024*1024',
      selectedStyle: '<auto>',
      ref_img: '',
      imageCount: 1,
      currentTaskId: null,
      pollingInterval: null,
      sizeOptions: [
        { label: '1:1', value: '1024*1024' },
        { label: '3:4', value: '768*1024' },
        { label: '4:3', value: '1024*768' },
        { label: '9:16', value: '576*1024' },
        { label: '16:9', value: '1024*576' }
      ],
      styleOptions: [
        { label: '自动', value: '<auto>' },
        { label: '写实', value: 'realistic' },
        { label: '油画', value: 'oilpainting' },
        { label: '水彩', value: 'watercolor' },
        { label: '素描', value: 'sketch' },
        { label: '动漫', value: 'anime' },
        { label: '复古', value: 'vintage' }
      ],
      task_metrics: {
        TOTAL: 0,
        SUCCESS: 0,
        FAILED: 0
      }
    }
  },
  methods: {
    triggerFileInput() {
      this.$refs.fileInput.click();
    },

    handleFileChange(e) {
      const file = e.target.files[0];
      if (!file) return;

      // Check file size (max 5MB)
      if (file.size > 5 * 1024 * 1024) {
        this.$message.error('文件大小不能超过 5MB');
        return;
      }

      const reader = new FileReader();
      reader.onload = (e) => {
        this.referenceImage = e.target.result;
      };
      reader.readAsDataURL(file);
    },

    removeImage() {
      this.referenceImage = null;
      this.$refs.fileInput.value = '';
    },

    handleEnterKey(e) {
      if (e.shiftKey) {
        const textarea = e.target;
        const start = textarea.selectionStart;
        const end = textarea.selectionEnd;
        const value = textarea.value;

        this.prompt = value.substring(0, start) + '\n' + value.substring(end);

        this.$nextTick(() => {
          textarea.selectionStart = textarea.selectionEnd = start + 1;
        });
      } else {
        e.preventDefault();
        if (!this.isGenerating && this.prompt.trim()) {
          this.generateImage();
        }
      }
    },
    async generateImage() {
      if (!this.prompt.trim()) return;

      this.isGenerating = true;
      this.images = [];
      const input = {
        prompt: this.prompt,
      }
      if (this.ref_img) {
        input.ref_img = this.ref_img
      }
      this.task_metrics = {
        TOTAL: this.imageCount,
        SUCCESS: 0,
        FAILED: 0
      }
      try {
        const response = await axios({
          url: '/api/v1/services/aigc/text2image/image-synthesis',
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer sk-c485ada860234fc2b99073ace395b307`,
            'X-DashScope-Async': 'enable'
          },
          data: {
            "model": "wanx-v1", //必填项
            "input": input,
            "parameters": {
              "style": this.selectedStyle,
              "size": this.imageRatio,
              "n": this.imageCount,
              // "seed": 42,
              // "ref_strength": 0.5,
              // "ref_mode": "repaint"
            }
          }
        });
        console.log(response)
        const data = await response.data;
        if (data.output && data.output.task_id) {
          this.currentTaskId = data.output.task_id;
          this.checkTaskStatus()
          this.startPolling();
        } else {
          throw new Error('获取任务ID失败');
        }
      } catch (error) {
        this.$message.error(error.message || '图片生成失败，请重试');
        this.isGenerating = false;
      }
    },

    async checkTaskStatus() {
      try {
        const response = await axios({
          method: 'GET',
          url: `/api/v1/tasks/${this.currentTaskId}`,
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer sk-c485ada860234fc2b99073ace395b307`,
            'X-DashScope-Async': 'enable'
          },
        });
        console.log(response.data,'response.data.data')
        if (response.data) {
          const taskData = response.data.output;
          /**
           * {
           *     "request_id": "6c25b630-a408-9529-a297-33f2c9e12830",
           *     "output": {
           *         "task_id": "f5b2182f-6e5f-4ca7-9b7e-8e132b69fc20",
           *         "task_status": "RUNNING",
           *         "submit_time": "2025-03-13 12:35:23.225",
           *         "scheduled_time": "2025-03-13 12:35:23.247",
           *         "task_metrics": {
           *             "TOTAL": 3,
           *             "SUCCEEDED": 2,
           *             "FAILED": 0
           *         }
           *     }
           * }
           */
          if (taskData.task_status === 'SUCCEEDED') {
            // Task completed successfully
            this.stopPolling();
            this.isGenerating = false;
            if (taskData.results) {
              this.images = taskData.results.map(result => result.url);
            }
          } else if (taskData.task_status === 'FAILED') {
            // Task failed
            this.stopPolling();
            this.isGenerating = false;
            throw new Error(taskData.message || '图片生成失败');
          } else if (taskData.task_status === 'RUNNING') {

          }
        }
      } catch (error) {
        this.stopPolling();
        this.isGenerating = false;
        this.$message.error(error.message || '获取任务状态失败');
      }
    },

    startPolling() {
      this.pollingInterval = setInterval(() => {
        if (this.currentTaskId) {
          this.checkTaskStatus();
        }
      }, 5000); // Poll every 2 seconds
    },

    stopPolling() {
      if (this.pollingInterval) {
        clearInterval(this.pollingInterval);
        this.pollingInterval = null;
      }
      this.currentTaskId = null;
    },
    downloadImage(imageUrl, index) {
      const link = document.createElement('a');
      link.href = imageUrl;
      link.download = `wanxiang-${Date.now()}-${index + 1}.png`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  },
  beforeDestroy() {
    this.stopPolling();
  }
}
</script>

<style lang="scss" scoped>
.wanxiang-container {
  height: 100%;
  display: flex;
  background-color: #f7f7f7;
}

.left-panel {
  width: 340px;
  padding: 20px;
  border-right: 1px solid #e4e4e4;
  background: white;
  display: flex;
  flex-direction: column;
  gap: 20px;

  .page-title {
    font-size: 16px;
    font-weight: normal;
    color: #302e34;
    margin: 0;
  }
}

.right-panel {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.input-section {
  flex-grow: 1;
  overflow: auto;
  display: flex;
  flex-direction: column;
  padding:6px;

  .prompt-input {
    margin-bottom: 20px;

    .custom-input {
      :deep(.el-textarea__inner) {
        border: none;
        border-radius: 8px;
        padding: 12px;
        font-size: 14px;
        line-height: 1.6;
        resize: none;
        background: #f5f7fa;
        color: #302e34;
        min-height: 120px !important;
        &:focus {
          background: white;
          box-shadow: 0 0 0 1px #7E4CE0;
        }
        &::placeholder {
          color: #999;
          line-height: 1.6;
        }
      }
    }
  }

}
.button-group {
  width: 100%;
  flex-shrink: 0;
  margin-top: 20px;
  display: flex;
  gap: 12px;

  .generate-btn {
    flex: 1;
    background: #7E4CE0;
    border-color: #7E4CE0;
    &:hover {
      background: darken(#7E4CE0, 5%);
    }
  }

  .clear-btn {
    width: 80px;
  }
}

.options-panel {
  margin: 0;
  .option-group {
    margin: 0;

    .option-title {
      font-size: 13px;
      color: #999;
      margin-bottom: 12px;
      padding-left: 4px;
    }

    .size-options,
    .style-options {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 8px;
      width: 100%;
      padding: 4px;
      margin-bottom: 24px;

      .size-option,
      .style-option {
        height: 32px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 16px;
        cursor: pointer;
        user-select: none;
        font-size: 13px;
        color: #666;
        background: #f5f7fa;
        transition: all 0.2s;
        padding: 0 16px;

        &:hover {
          background: #eef1f6;
        }

        &.is-active {
          background: #7E4CE0;
          color: white;
          font-weight: 500;
        }
      }
    }

    .style-options {
      grid-template-columns: repeat(3, 1fr);
    }

    .count-input {
      padding: 4px;
      margin-bottom: 24px;

      :deep(.el-input-number) {
        width: 100%;
      }
    }

    .upload-area {
      width: 100%;
      height: 120px;
      border: 2px dashed #dcdfe6;
      border-radius: 8px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      transition: all 0.2s;
      margin-bottom: 24px;
      background: #f5f7fa;
      position: relative;
      overflow: hidden;

      &:hover {
        border-color: #7E4CE0;
        background: #f0f7ff;

        .upload-icon {
          color: #7E4CE0;
        }
      }

      &.has-image {
        border-style: solid;
        background: white;

        &:hover .image-actions {
          opacity: 1;
        }
      }

      .upload-icon {
        font-size: 24px;
        color: #909399;
        margin-bottom: 8px;
      }

      .upload-text {
        font-size: 13px;
        color: #666;
      }

      .preview-image {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }

      .image-actions {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0, 0, 0, 0.6);
        padding: 8px;
        display: flex;
        justify-content: center;
        opacity: 0;
        transition: opacity 0.2s;
      }
    }
  }
}

.gallery-section {
  .image-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 20px;

    &.single-image {
      grid-template-columns: minmax(auto, 512px);
      justify-content: center;
    }
  }

  .image-item {
    position: relative;
    aspect-ratio: 1;
    border-radius: 12px;
    overflow: hidden;
    background: #f5f7fa;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    transition: transform 0.2s;

    &:hover {
      transform: translateY(-2px);

      .image-actions {
        opacity: 1;
      }
    }

    .el-image {
      width: 100%;
      height: 100%;
    }

    .image-actions {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      padding: 12px;
      background: linear-gradient(to top, rgba(0,0,0,0.7), transparent);
      display: flex;
      justify-content: center;
      opacity: 0;
      transition: opacity 0.3s;

      .el-button {
        color: white;
        font-size: 14px;
        &:hover {
          color: #7E4CE0;
        }
      }
    }
  }
}

.empty-state {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #909399;
  padding: 40px;

  i {
    font-size: 48px;
    margin-bottom: 16px;
    color: #dcdfe6;
  }

  p {
    font-size: 14px;
    color: #909399;
    margin: 0;
  }
}

.image-placeholder {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  color: #dcdfe6;

  i {
    font-size: 32px;
  }

  .button-group {
    padding: 20px 0;
    margin-top: auto;
    display: flex;
    border-top: 1px solid #f0f0f0;

    .generate-btn {
      flex: 1;
      height: 40px;
      background: #7E4CE0;
      border-color: #7E4CE0;
      border-radius: 20px;
      font-size: 14px;
      font-weight: 500;

      &:hover {
        background: darken(#7E4CE0, 5%);
      }

      &:disabled {
        background: #c0c4cc;
        border-color: #c0c4cc;
        color: white;
        opacity: 0.6;
      }

      &.is-loading {
        background: #7E4CE0;
        border-color: #7E4CE0;
        opacity: 0.8;
      }
    }
  }
}
</style>
